﻿using Ionic.Zip;
using Newtonsoft.Json.Linq;
using NLog;
using Simple.ClientWindowsServer;
using Simple.Framework.Configuration;
using Simple.PrettyClient;
using System.IO;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text;
using System.Text.Unicode;

namespace Simple.FileBackClient
{
	internal class Program
	{
		static void Main(string[] args)
		{
			CompressMulti(@"F:\文档\Info\sql", "test.zip",true);
			//head    2字节
			//length  2字节
			//cmd     一个字节    OxF=15登录  0x10=16 开始文件传输 0x11=17 传输中 0x12=18  传输完成

			//tail    2字节
			byte[] buffer = new byte[2] { 225, 1 };

			int i = BitConverter.ToInt16(buffer, 0);
			//0 0 0 0 0  0  0  0   0
			//1 2 4 8 16 32 64 128 225
			IClient host = Client.BuilderClient().Regster((container) =>
					{
						//容器模块，注册需要实例的对象，容器可以自动创建对象，解决对象的依赖。
						//container.RegisterSingleton<IConfiguration, IDTConfiguration>();

						Logger logger = NLog.LogManager.GetCurrentClassLogger();
						container.RegistSingletonInstance<ILogger, Logger>(logger);
					}).
					RegisterSchedule((scheduleManager) =>
					{
						//注册任务
						//任务是固定时间间隔执行
						//一个任务周期为 任务中逻辑时间+等待时间
						//通常任务时间比较少，适合做心跳检查
						scheduleManager.Register<BackupsSchedule>();
						scheduleManager.Register<BackupsDatabaseSchedule>();
						//scheduleManager.Register<CheckHeartSchedule>();
						//scheduleManager.Register<CheckCommandSchedule>();

					}).Start().
					UseWindowsService();
			Console.ReadLine();
		}


		public static bool CompressMulti(string directory, string strZipName, bool isDirStruct = false)
		{
			if (directory == null)
			{
				throw new ArgumentNullException("list");
			}
			if (!Directory.Exists(directory))
			{
				return false;
			}
			if (string.IsNullOrEmpty(strZipName))
			{
				throw new ArgumentNullException(strZipName);
			}
			try
			{
				//设置编码，解决压缩文件时中文乱码
				using (var zip = new ZipFile(Encoding.UTF8))
				{
					zip.UseZip64WhenSaving = Zip64Option.AsNecessary;//or Uncompressed size, or offset exceeds the maximum value.Consider setting the UseZip64WhenSaving property on the ZipFile instance.
					if (isDirStruct)
					{
						foreach (var path in Directory.GetDirectories(directory))
						{
							var fileName = Path.GetFileName(path);
							zip.AddDirectory(path, fileName);
						}

						foreach (var path in Directory.GetFiles(directory))
						{
							zip.AddFile(path,"");
						}
					}
					else
					{
						zip.AddDirectory(directory);
					}

					zip.Save($"F:\\笔记\\{strZipName}");
					return true;
				}
			}
			catch (Exception ex)
			{
				throw new Exception(ex.Message);
			}
		}

	}

}
